/*
 * FreeRTOS Kernel V10.5.1
 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * SPDX-License-Identifier: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * https://www.FreeRTOS.org
 * https://github.com/FreeRTOS
 *
 */

#include <stdlib.h>
#include <string.h>

/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
 * all the API functions to use the MPU wrappers.  That should only be done when
 * task.h is included from an application file. */
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE

#include "FreeRTOS.h"
#include "task.h"

#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE

#ifndef configHEAP_CLEAR_MEMORY_ON_FREE
    #define configHEAP_CLEAR_MEMORY_ON_FREE    0
#endif

/* Block sizes must not get too small. */
#define heapMINIMUM_BLOCK_SIZE    ((size_t) (xHeapStructSize << 1))

/* Assumes 8bit bytes! */
#define heapBITS_PER_BYTE         ((size_t)8)

/* Max value that fits in a size_t type. */
#define heapSIZE_MAX              (~((size_t)0))

/* Check if multiplying a and b will result in overflow. */
#define heapMULTIPLY_WILL_OVERFLOW( a, b )    ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )

/* Check if adding a and b will result in overflow. */
#define heapADD_WILL_OVERFLOW(a, b)         ((a) > (heapSIZE_MAX - (b)))

/* MSB of the xBlockSize member of an BlockLink_t structure is used to track
 * the allocation status of a block.  When MSB of the xBlockSize member of
 * an BlockLink_t structure is set then the block belongs to the application.
 * When the bit is free the block is still part of the free heap space.
 * heapBLOCK_ALLOCATED_BITMASK : 只为0x80000000，用来表示内存的空闲状态
 */
#define heapBLOCK_ALLOCATED_BITMASK    (((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1))
#define heapBLOCK_SIZE_IS_VALID(xBlockSize)    (((xBlockSize) & heapBLOCK_ALLOCATED_BITMASK) == 0)
#define heapBLOCK_IS_ALLOCATED(pxBlock)        (((pxBlock->xBlockSize) & heapBLOCK_ALLOCATED_BITMASK) != 0)
#define heapALLOCATE_BLOCK(pxBlock)            ((pxBlock->xBlockSize) |= heapBLOCK_ALLOCATED_BITMASK)
#define heapFREE_BLOCK(pxBlock)                ((pxBlock->xBlockSize) &= ~heapBLOCK_ALLOCATED_BITMASK)

/*-----------------------------------------------------------*/

/* Allocate the memory for the heap. */
#if (configAPPLICATION_ALLOCATED_HEAP == 1)

/* The application writer has already defined the array used for the RTOS
* heap - probably so it can be placed in a special segment or address. */
    extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
#else
    PRIVILEGED_DATA static uint8_t ucHeap[configTOTAL_HEAP_SIZE];
#endif /* configAPPLICATION_ALLOCATED_HEAP */

/**
 * Define the linked list structure.  This is used to link free blocks in order
 * of their memory address.
 * 空闲块链表节点
 */
typedef struct A_BLOCK_LINK
{
    struct A_BLOCK_LINK * pxNextFreeBlock; /* 指向一下个空闲块节点 */
    size_t xBlockSize;                     /* 空闲块的长度 */
}BlockLink_t;

/*
 * Inserts a block of memory that is being freed into the correct position in
 * the list of free memory blocks.  The block being freed will be merged with
 * the block in front it and/or the block behind it if the memory blocks are
 * adjacent to each other.
 */
static void prvInsertBlockIntoFreeList(BlockLink_t * pxBlockToInsert) PRIVILEGED_FUNCTION;

/*
 * Called automatically to setup the required heap structures the first time
 * pvPortMalloc() is called.
 */
static void prvHeapInit(void) PRIVILEGED_FUNCTION;

/*-----------------------------------------------------------*/

/* The size of the structure placed at the beginning of each allocated memory
 * block must by correctly byte aligned.
 * 计算出sizeof(BlockLink_t)对齐到portBYTE_ALIGNMENT后的大小
 */
static const size_t xHeapStructSize = (sizeof(BlockLink_t) + ((size_t) (portBYTE_ALIGNMENT - 1))) & ~((size_t)portBYTE_ALIGNMENT_MASK);

/* Create a couple of list links to mark the start and end of the list. */
PRIVILEGED_DATA static BlockLink_t xStart;
PRIVILEGED_DATA static BlockLink_t * pxEnd = NULL;

/* 记录系统空闲的内存 */
PRIVILEGED_DATA static size_t xFreeBytesRemaining = 0U;
/* 记录系统最小空闲内存块的大小 */
PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = 0U;
PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = 0;
PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = 0;

/**
 *@xWantedSize: 申请内存长度
 */
void *pvPortMalloc(size_t xWantedSize)
{
    BlockLink_t * pxBlock;
    BlockLink_t * pxPreviousBlock;
    BlockLink_t * pxNewBlockLink;
    void * pvReturn = NULL;
    size_t xAdditionalRequiredSize;

    vTaskSuspendAll();
    {
        /* If this is the first call to malloc then the heap will require
         * initialisation to setup the list of free blocks.
         * 第一次调用，初始化堆
         */
        if (pxEnd == NULL)
        {
            prvHeapInit();
        }

        if (xWantedSize > 0)
        {
            /* The wanted size must be increased so it can contain a BlockLink_t
             * structure in addition to the requested amount of bytes. Some
             * additional increment may also be needed for alignment.
             * 每一个空闲块都需要一个BlockLink_t来管理，本身该结构也需要内存，因此
             * 每一个申请的内存，会额外的增加xHeapStructSize长度
             */
            xAdditionalRequiredSize = xHeapStructSize + portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK);

            if (heapADD_WILL_OVERFLOW(xWantedSize, xAdditionalRequiredSize) == 0)
            {
                xWantedSize += xAdditionalRequiredSize;
            }
            else
            {
                xWantedSize = 0;
            }
        }

        /* Check the block size we are trying to allocate is not so large that the
         * top bit is set.  The top bit of the block size member of the BlockLink_t
         * structure is used to determine who owns the block - the application or
         * the kernel, so it must be free. */
        if (heapBLOCK_SIZE_IS_VALID(xWantedSize) != 0)
        {
            if ((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining))
            {
                /* Traverse the list from the start (lowest address) block until
                 * one of adequate size is found. */
                pxPreviousBlock = &xStart;
                pxBlock = xStart.pxNextFreeBlock;

                /* 找到满足内存申请的空闲块的前一个链表节点 */
                while((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL))
                {
                    pxPreviousBlock = pxBlock;
                    pxBlock = pxBlock->pxNextFreeBlock;
                }

                /* If the end marker was reached then a block of adequate size
                 * was not found. */
                if (pxBlock != pxEnd)
                {
                    /* Return the memory space pointed to - jumping over the
                     * BlockLink_t structure at its start. */
                    pvReturn = (void *) (((uint8_t *)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize);

                    /* This block is being returned for use so must be taken out
                     * of the list of free blocks.
                     * 该块已经被使用，从空闲链表中删除
                     */
                    pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;

                    /* *
                     * If the block is larger than required it can be split into
                     * two.
                     * 找到满足xWantedSize的空闲块，但是该块比较大，因此把剩余的内存，重新
                     * 加入到空闲链表中
                     */
                    if ((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE)
                    {
                        /* This block is to be split into two.  Create a new
                         * block following the number of bytes requested. The void
                         * cast is used to prevent byte alignment warnings from the
                         * compiler.
                         * 新块的起始地址
                         * */
                        pxNewBlockLink = (void *)(((uint8_t *) pxBlock) + xWantedSize);
                        configASSERT((((size_t)pxNewBlockLink) & portBYTE_ALIGNMENT_MASK) == 0);

                        /* Calculate the sizes of two blocks split from the
                         * single block.
                         * 新块的长度
                         */
                        pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
                        pxBlock->xBlockSize = xWantedSize;

                        /**
                         * Insert the new block into the list of free blocks.
                         * 新块插入到空闲链表
                         */
                        prvInsertBlockIntoFreeList(pxNewBlockLink);
                    }

                    /* 减少系统可用的内存 */
                    xFreeBytesRemaining -= pxBlock->xBlockSize;

                    /* 统计系统中最小空闲内存块 没进行一个内存分配，更新一次 */
                    if (xFreeBytesRemaining < xMinimumEverFreeBytesRemaining)
                    {
                        xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
                    }

                    /* The block is being returned - it is allocated and owned
                     * by the application and has no "next" block.
                     * 标记该pxBlock块已经被分配了
                     */
                    heapALLOCATE_BLOCK(pxBlock);
                    pxBlock->pxNextFreeBlock = NULL;
                    /* 统计内存分配成功的次数 */
                    xNumberOfSuccessfulAllocations++;
                }
            }
        }


        traceMALLOC(pvReturn, xWantedSize);
    }
    (void)xTaskResumeAll();

    #if (configUSE_MALLOC_FAILED_HOOK == 1)
    {
        if (pvReturn == NULL)
        {
            vApplicationMallocFailedHook();
        }
    }
    #endif

    configASSERT((((size_t) pvReturn) & (size_t) portBYTE_ALIGNMENT_MASK) == 0);

    /* 返回新申请内存的起始地址 */
    return pvReturn;
}


void vPortFree(void * pv)
{
    uint8_t * puc = (uint8_t *)pv;
    BlockLink_t * pxLink;

    if (pv != NULL)
    {
        /* The memory being freed will have an BlockLink_t structure immediately
         * before it. */
        puc -= xHeapStructSize;

        /* This casting is to keep the compiler from issuing warnings. */
        pxLink = (void *)puc;

        configASSERT(heapBLOCK_IS_ALLOCATED( pxLink) != 0);
        configASSERT(pxLink->pxNextFreeBlock == NULL);

        /* pxLink块是已经被分配的 */
        if (heapBLOCK_IS_ALLOCATED(pxLink) != 0)
        {
            if (pxLink->pxNextFreeBlock == NULL)
            {
                /* The block is being returned to the heap - it is no longer
                 * allocated.
                 * 清理掉pxLink已经分配标记(还原为空闲)
                 */
                heapFREE_BLOCK(pxLink);
                #if (configHEAP_CLEAR_MEMORY_ON_FREE == 1)
                {
                    (void)memset(puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize);
                }
                #endif

                vTaskSuspendAll();
                {
                    /* Add this block to the list of free blocks. */
                    xFreeBytesRemaining += pxLink->xBlockSize;
                    traceFREE(pv, pxLink->xBlockSize);
                    prvInsertBlockIntoFreeList(((BlockLink_t *)pxLink));
                    xNumberOfSuccessfulFrees++;
                }
                (void)xTaskResumeAll();
            }
        }
    }
}

/* 返回系统可用内存 */
size_t xPortGetFreeHeapSize(void)
{
    return xFreeBytesRemaining;
}

/* 返回系统最小空闲内存块长度 */
size_t xPortGetMinimumEverFreeHeapSize(void)
{
    return xMinimumEverFreeBytesRemaining;
}


void vPortInitialiseBlocks(void)
{

}

void *pvPortCalloc(size_t xNum, size_t xSize)
{
    void * pv = NULL;

    if (heapMULTIPLY_WILL_OVERFLOW(xNum, xSize) == 0)
    {
        pv = pvPortMalloc(xNum * xSize);

        if (pv != NULL)
        {
            (void)memset(pv, 0, xNum * xSize);
        }
    }

    return pv;
}

static void prvHeapInit(void)
{
    BlockLink_t * pxFirstFreeBlock;
    uint8_t * pucAlignedHeap;
    portPOINTER_SIZE_TYPE uxAddress;
    size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;

    /* Ensure the heap starts on a correctly aligned boundary. */
    uxAddress = (portPOINTER_SIZE_TYPE)ucHeap;

    /**
     * 起始地址和大小都不是portBYTE_ALIGNMENT_MASK对齐情况
     * 对于M4架构来说，是8字节对齐
     */
    if ((uxAddress & portBYTE_ALIGNMENT_MASK) != 0)
    {
        /* 堆的起始地址对齐到8字节 */
        uxAddress += (portBYTE_ALIGNMENT - 1);
        uxAddress &= ~((portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK);
        /* 重新计算对齐后，整个堆的大小 */
        xTotalHeapSize -= (uxAddress - (portPOINTER_SIZE_TYPE)ucHeap);
    }

    /* 指向对齐后的堆起始地址 */
    pucAlignedHeap = (uint8_t *)uxAddress;

    /**
     * xStart is used to hold a pointer to the first item in the list of free
     * blocks.  The void cast is used to prevent compiler warnings.
     * 计算起始内存的地址
     */
    xStart.pxNextFreeBlock = (void *)pucAlignedHeap;
    xStart.xBlockSize = (size_t)0;

    /**
     * pxEnd is used to mark the end of the list of free blocks and is inserted
     * at the end of the heap space.
     * 计算结束内存的地址,并将pxEnd指针存放在堆的末尾
     */
    uxAddress = ((portPOINTER_SIZE_TYPE)pucAlignedHeap) + xTotalHeapSize;
    uxAddress -= xHeapStructSize;
    uxAddress &= ~((portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK);
    pxEnd = (BlockLink_t *) uxAddress;
    pxEnd->xBlockSize = 0;
    pxEnd->pxNextFreeBlock = NULL;

    /* To start with there is a single free block that is sized to take up the
     * entire heap space, minus the space taken by pxEnd.
     * 开始，将整个堆当做一个空闲块
     */
    pxFirstFreeBlock = (BlockLink_t * ) pucAlignedHeap;
    /* 整个空闲块的长度为堆空间 */
    pxFirstFreeBlock->xBlockSize = (size_t)(uxAddress - (portPOINTER_SIZE_TYPE)pxFirstFreeBlock);
    pxFirstFreeBlock->pxNextFreeBlock = pxEnd;

    /**
     * Only one block exists - and it covers the entire usable heap space.
     */
    xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
    xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
}

/**
 * 内存块插入空闲内存块链表
 */
static void prvInsertBlockIntoFreeList(BlockLink_t * pxBlockToInsert)
{
    BlockLink_t * pxIterator;
    uint8_t * puc;

    /**
     * Iterate through the list until a block is found that has a higher address
     * than the block being inserted.
     * 从系统起始堆位置，开始遍历, 找到插入的位置, 该链表为地址从小到大的有序链表
     */
    pxIterator=&xStart;
    while (pxIterator->pxNextFreeBlock < pxBlockToInsert)
        pxIterator=pxIterator->pxNextFreeBlock;

    /* Do the block being inserted, and the block it is being inserted after
     * make a contiguous block of memory?
     * 找到了链表插入的位置
     */
    puc = (uint8_t *)pxIterator;

    /**
     * 1. 刚好puc跟pxBlockToInsert相邻, 并且为pxIterator的前驱
     */
    if ((puc + pxIterator->xBlockSize) == (uint8_t *)pxBlockToInsert)
    {
        /* 扩展pxIterator管理内存块的长度 */
        pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
        /*
         * 由于pxBlockToInsert可以和pxIterator向前合并，合并后pxBlockToInsert将不复存在，
         * 因此，重新更新插入块的地址
         */
        pxBlockToInsert = pxIterator;
    }

    /* Do the block being inserted, and the block it is being inserted before
     * make a contiguous block of memory? */
    puc = (uint8_t *)pxBlockToInsert;

    /**
     * 1. 刚好puc跟pxBlockToInsert相邻, 并且为pxIterator的后继
     * 2. 也有可能是第一个块的进一步合并
     */
    if ((puc + pxBlockToInsert->xBlockSize) == (uint8_t *)pxIterator->pxNextFreeBlock)
    {
        if (pxIterator->pxNextFreeBlock != pxEnd)
        {
            /* 可以和后面的块进行合并 */
            pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
            /*
             * 由于pxBlockToInsert可以和pxIterator向后合并，合并后pxIterator将不复存在，
             * 因此，重新更新pxBlockToInsert下一个空闲块的地址
             */
            pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
        }
        else
        {
            pxBlockToInsert->pxNextFreeBlock = pxEnd;
        }
    }
    else
    {
        pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
    }

    /* If the block being inserted plugged a gab, so was merged with the block
     * before and the block after, then it's pxNextFreeBlock pointer will have
     * already been set, and should not be set here as that would make it point
     * to itself.
     * pxIterator与pxBlockToInsert这两块空闲内存不连续，存在gap情况
     */
    if (pxIterator != pxBlockToInsert)
    {
        pxIterator->pxNextFreeBlock = pxBlockToInsert;
    }
}

void vPortGetHeapStats(HeapStats_t * pxHeapStats)
{
    BlockLink_t * pxBlock;
    size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY;

    vTaskSuspendAll();
    {
        pxBlock = xStart.pxNextFreeBlock;

        /* pxBlock will be NULL if the heap has not been initialised.  The heap
         * is initialised automatically when the first allocation is made. */
        if (pxBlock != NULL)
        {
            while(pxBlock != pxEnd)
            {
                /* Increment the number of blocks and record the largest block seen
                 * so far. */
                xBlocks++;

                /* 找到最大空闲块 */
                if (pxBlock->xBlockSize > xMaxSize)
                {
                    xMaxSize = pxBlock->xBlockSize;
                }
                /* 找到最大空闲块 */
                if (pxBlock->xBlockSize < xMinSize)
                {
                    xMinSize = pxBlock->xBlockSize;
                }

                pxBlock = pxBlock->pxNextFreeBlock;
            }
        }
    }
    (void) xTaskResumeAll();

    /* 设置系统中最大空闲内存块长度 */
    pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
    /* 设置系统中最小内存块长度 */
    pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
    /* 设置系统中存在的空闲块个数 */
    pxHeapStats->xNumberOfFreeBlocks = xBlocks;

    taskENTER_CRITICAL();
    {
        pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
        pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
        pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
        pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
    }
    taskEXIT_CRITICAL();
}
